import { shallowReactive, ref } from 'vue';
import { actionSheetController } from '@ionic/vue';
import { menuController } from '@ionic/core';
import * as ionicons from 'ionicons/icons';
import { IPSDEToolbarItem, IPSUIAction } from '@ibiz/dynamic-model-api';
import { MobToolbarEvents, IParam, MobToolbarCtrlController, IMobToolbarCtrlController } from 'ibz-core';
import { Util, ViewTool } from 'ibz-core';
import { AppMobToolbarProps } from 'ibz-core';
import { GenerateComponent } from '../component-base';
import { CtrlComponentBase } from './ctrl-component-base';

/**
 * @description 视图工具栏
 * @export
 * @class AppMobToolbar
 * @extends {CtrlComponentBase<AppMobToolbarProps>}
 */
export class AppMobToolbar extends CtrlComponentBase<AppMobToolbarProps> {
  /**
   * @description 部件控制器
   * @protected
   * @type {IMobToolbarCtrlController}
   * @memberof AppMobToolbar
   */
  protected c!: IMobToolbarCtrlController;

  /**
   * @description 工具栏样式
   * @type {string}
   * @memberof AppMobToolbar
   */
  public toolbarStyle!: string;

  /**
   * @description 工具栏弹出方向
   * @type {string}
   * @memberof AppMobToolbar
   */
  public toolbarSide: string = '';

  /**
   * @description 工具栏弹出菜单引用
   * @type {IParam}
   * @memberof AppMobToolbar
   */
  public toolbarRef: IParam = {};

  /**
   * @description 工具栏菜单uuid
   * @type {string}
   * @memberof AppMobToolbar
   */
  public toolbarID: string = Util.createUUID();

  /**
   * @description 工具栏内容uuid
   * @type {string}
   * @memberof AppMobToolbar
   */
  public contentId: string = Util.createUUID();

  /**
   * @description 设置响应式
   * @memberof AppMobToolbar
   */
  setup() {
    this.toolbarRef = ref(null);
    this.c = shallowReactive<MobToolbarCtrlController>(
      this.getCtrlControllerByType('TOOLBAR') as MobToolbarCtrlController,
    );
    super.setup();
  }

  /**
   * @description 部件初始化
   * @memberof AppMobToolbar
   */
  init() {
    super.init();
    this.toolbarStyle = this.c.controlInstance.toolbarStyle ? this.c.controlInstance.toolbarStyle : 'TOOLBAR';
    this.calcToolbarStyleParams();
  }

  /**
   * @description 打开工具栏
   * @memberof AppMobToolbar
   */
  public async openToolbar() {
    if (Object.is(this.toolbarSide, 'bottom')) {
      this.openBottomToolbar();
    } else {
      await menuController.enable(true, this.toolbarID);
      menuController.open(this.toolbarID);
    }
  }

  /**
   * @description 关闭工具栏
   * @memberof AppMobToolbar
   */
  public closeToolbar() {
    if (Object.is(this.toolbarStyle, 'MOBNAVRIGHTMENU') || Object.is(this.toolbarStyle, 'MOBNAVLEFTMENU')) {
      menuController.close(this.toolbarID);
    }
  }

  /**
   * @description 工具栏项点击
   * @param {string} name
   * @param {MouseEvent} e
   * @memberof AppMobToolbar
   */
  public itemClick(item: any, e: MouseEvent): void {
    this.emitCtrlEvent({
      action: MobToolbarEvents.TOOLBAR_CLICK,
      controlname: this.c.controlInstance.name,
      data: { tag: `${this.c.name}_${item.name}_click`, event: e },
    });
    this.closeToolbar();
  }

  /**
   * @description 获取图标
   * @param {IPSDEToolbarItem} item
   * @return {*}  {*}
   * @memberof AppMobToolbar
   */
  public getIcon(item: IPSDEToolbarItem): any {
    if (item.getPSSysImage()?.cssClass) {
      const iconName = Util.formatCamelCase(ViewTool.setIcon(item.getPSSysImage()?.cssClass as string));
      return iconName ? (ionicons as any)[iconName] : null;
    } else {
      return null;
    }
  }

  /**
   * @description 计算工具栏样式参数
   * @memberof AppMobToolbar
   */
  public calcToolbarStyleParams() {
    switch (this.toolbarStyle) {
      case 'MOBNAVRIGHTMENU':
        this.toolbarSide = 'end';
        break;
      case 'MOBNAVLEFTMENU':
        this.toolbarSide = 'start';
        break;
      case 'MOBBOTTOMMENU':
        this.toolbarSide = 'bottom';
        break;
    }
  }

  /**
   * @description 绘制菜单工具项
   * @protected
   * @param {*} item
   * @return {*}  {*}
   * @memberof AppMobToolbar
   */
  protected renderToolbarItem(item: any): any {
    if (item.hiddenItem || item.noPrivHidden) {
      return null;
    }
    if (item.getPSSysPFPlugin()?.pluginCode) {
      const ctrlItemPluginInstance = App.getPluginService().getCtrlItemPluginByTag(item.getPSSysPFPlugin()?.pluginCode);
      if (ctrlItemPluginInstance) {
        return ctrlItemPluginInstance.renderItem(item, this.c, this);
      }
    } else {
      const itemStyle: IParam = { width: item.width ? item.width + 'px' : 'auto' };
      const cssName: string = item.getPSSysCss()?.cssName || '';
      return (
        <ion-item
          disabled={item.noPrivDisabled}
          style={itemStyle}
          class={cssName}
          onClick={(e: any) => this.itemClick(item, e)}
        >
          {item.showIcon ? <app-icon icon={item.getPSSysImage()}></app-icon> : null}
          {item.showCaption ? (
            <ion-label>{this.$tl(item.getCapPSLanguageRes()?.lanResTag, item.caption)}</ion-label>
          ) : null}
        </ion-item>
      );
    }
  }

  /**
   * @description 绘制侧边工具栏
   * @protected
   * @return {*}
   * @memberof AppMobToolbar
   */
  protected renderSideToolbar() {
    if (!this.toolbarSide || Object.is(this.toolbarSide, 'bottom')) {
      return null;
    }
    return this.renderToolbar(this.toolbarSide);
  }

  /**
   * @description 绘制工具栏按钮
   * @protected
   * @return {*}  {*}
   * @memberof AppMobToolbar
   */
  protected renderToolbarButton(): any {
    if (
      !Object.is(this.toolbarStyle, 'MOBNAVRIGHTMENU') &&
      !Object.is(this.toolbarStyle, 'MOBNAVLEFTMENU') &&
      !Object.is(this.toolbarStyle, 'MOBBOTTOMMENU')
    ) {
      App.getNoticeService().warning(this.$tl('widget.mobtoolbar.notsupport', '工具栏样式暂未支持！！！'));
      return null;
    }
    return (
      <ion-button id={this.contentId} onClick={() => this.openToolbar()} expand='block'>
        <app-icon name='ellipsis-horizontal'></app-icon>
      </ion-button>
    );
  }

  /**
   * @description 绘制侧边工具栏
   * @param {string} side
   * @return {*}
   * @memberof AppMobToolbar
   */
  public renderToolbar(side: string) {
    if (this.c.toolbarModels.length == 0) {
      return null;
    }
    return (
      <ion-menu
        slot='fixed'
        class='app-toolbar-popup'
        ref={this.toolbarRef}
        side={side}
        contentId={this.contentId}
        menuId={this.toolbarID}
      >
        <ion-list>
          {this.c.toolbarModels.map((item: IPSDEToolbarItem) => {
            return this.renderToolbarItem(item);
          })}
        </ion-list>
      </ion-menu>
    );
  }

  /**
   * @description 打开底部菜单
   * @memberof AppMobToolbar
   */
  public async openBottomToolbar() {
    const buttons: any[] = [];
    this.c.toolbarModels.forEach((item: any) => {
      const cssName: string = item.getPSSysCss()?.cssName || '';
      const icon: string = this.getIcon(item);
      buttons.push({
        text: this.$tl(item.getCapPSLanguageRes()?.lanResTag, item.caption),
        icon: icon,
        cssClass: cssName,
        handler: (e: any) => {
          this.itemClick(item, e);
        },
      });
    });
    const actionSheet = await actionSheetController.create({
      buttons: buttons,
    });
    await actionSheet.present();
  }

  /**
   * @description 绘制平铺工具栏
   * @protected
   * @return {*}
   * @memberof AppMobToolbar
   */
  protected renderDefaultToolbar() {
    if (this.c.toolbarModels.length == 0) {
      return null;
    }
    if (Object.is(this.toolbarStyle, 'TOOLBAR')) {
      return this.c.toolbarModels.map((item: any) => {
        if (item.hiddenItem || item.noPrivHidden) {
          return null;
        }
        if (item.getPSSysPFPlugin()?.pluginCode && !App.isPreviewMode()) {
          const ctrlItemPluginInstance = App.getPluginService().getCtrlItemPluginByTag(
            item.getPSSysPFPlugin()?.pluginCode,
          );
          if (ctrlItemPluginInstance) {
            return ctrlItemPluginInstance.renderItem(item, this.c, this);
          }
        } else {
          const buttonStyle: IParam = { width: item.width ? item.width + 'px' : 'auto' };
          const cssName: string = item.getPSSysCss()?.cssName || '';
          return (
            <ion-button
              disabled={item.noPrivDisabled}
              style={buttonStyle}
              class={cssName}
              onClick={(e: any) => this.itemClick(item, e)}
              expand='block'
            >
              <app-icon icon={item.getPSSysImage()}></app-icon>
              {this.$tl(item.getCapPSLanguageRes()?.lanResTag, item.caption)}
            </ion-button>
          );
        }
      });
    } else {
      return this.renderToolbarButton();
    }
  }

  /**
   * @description 绘制工具栏
   * @return {*}  {*}
   * @memberof AppMobToolbar
   */
  public render(): any {
    if (!this.controlIsLoaded.value) {
      return null;
    }
    const dir = Object.is(this.c.name, 'lefttoolbar') ? 'start' : 'end';
    return [
      <ion-toolbar class={{ ...this.classNames }} slot='fixed'>
        <ion-buttons slot={dir}>{this.renderDefaultToolbar()}</ion-buttons>
      </ion-toolbar>,
      this.renderSideToolbar(),
    ];
  }
}

// 应用菜单组件
export const AppMobToolbarComponent = GenerateComponent(AppMobToolbar, Object.keys(new AppMobToolbarProps()));
